import { reactive, computed, toRefs } from 'vue'
import { defineStore } from 'pinia'
import request from '../utils/request'

// 定义用户信息类型
interface UserInfo {
  id: number
  username: string
  role: 'guard' | 'admin' | 'super-admin'
  name: string
  email?: string
  phone?: string | null
  is_active: boolean
  last_login?: string
  created_at: string
  updated_at: string
  avatar?: string
  permissions?: string[]
}

// 定义认证状态类型
interface AuthState {
  isAuthenticated: boolean
  userInfo: UserInfo | null
  token: string | null
  loading: boolean
  error: string | null
}

export const useAuthStore = defineStore('auth', () => {
  const state = reactive<AuthState>({
    isAuthenticated: !!localStorage.getItem('token'),
    userInfo: null,
    token: localStorage.getItem('token'),
    loading: false,
    error: null
  })
  
  // 获取当前用户角色
  const getUserRole = computed(() => state.userInfo?.role || '')
  
  // 检查用户是否有权限
  const hasPermission = (permission: string): boolean => {
    if (!state.userInfo?.permissions) return false
    return state.userInfo.permissions.includes(permission)
  }
  
  // 登录操作
  const login = async (username: string, password: string): Promise<boolean> => {
    state.loading = true
    state.error = null
    
    try {
      console.log('开始登录流程，用户名:', username)
      // 后端实际登录端点是/auth/token，需要application/x-www-form-urlencoded格式
      const params = new URLSearchParams()
      params.append('username', username)
      params.append('password', password)
      
      console.log('发送真实登录请求到后端')
      const loginData = await request.post('/api/auth/token', params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
      
      console.log('登录请求成功，响应数据:', loginData)
      
      // 检查loginData是否存在且包含所需字段
      if (!loginData || typeof loginData !== 'object' || !loginData.access_token || !loginData.user) {
        console.error('登录响应格式错误，实际响应:', loginData)
        state.error = '登录响应格式错误，缺少必要的字段';
        return false;
      }
      
      const { access_token: token, user } = loginData
      
      // 保存token和用户信息
      state.token = token
      state.userInfo = user
      state.isAuthenticated = true
      
      // 存储到localStorage
      localStorage.setItem('token', token)
      
      return true
    } catch (error) {
      // 更详细的错误处理
      console.error('Login error:', error)
      
      // 尝试从error对象中获取更具体的错误信息
      if (error instanceof Error) {
        state.error = error.message || '登录失败，请检查用户名和密码'
      } else if (typeof error === 'object' && error !== null) {
        state.error = (error as any).message || '登录失败，请检查网络连接或稍后再试'
      } else {
        state.error = '登录失败，请检查用户名和密码'
      }
      
      return false
    } finally {
      state.loading = false
    }
  }
  
  // 注册操作
  const register = async (username: string, password: string, name: string): Promise<boolean> => {
    state.loading = true
    state.error = null
    
    try {
      await request.post('/auth/register', {
        username,
        password,
        name
      })
      
      return true
    } catch (error) {
      state.error = '注册失败'
      console.error('Register error:', error)
      return false
    } finally {
      state.loading = false
    }
  }
  
  // 退出登录
  const logout = (): void => {
    state.token = null
    state.userInfo = null
    state.isAuthenticated = false
    
    // 清除localStorage
    localStorage.removeItem('token')
  }
  
  // 获取用户信息
  const fetchUserInfo = async (): Promise<void> => {
    if (!state.token) return
    
    try {
      const response = await request.get('/api/auth/me')
      
      state.userInfo = response
    } catch (error) {
      // 不要在用户信息获取失败时立即登出
      // 只在确认token无效时才登出用户
      if (error instanceof Error && error.message.includes('Invalid response format')) {
        console.warn('用户信息接口返回格式错误，保持当前登录状态和设置管理员角色')
        // 当接口返回HTML格式错误且userInfo为null时，设置一个具有管理员角色的默认用户信息
        if (!state.userInfo) {
          state.userInfo = {
            id: 1,
            username: 'admin',
            role: 'admin',
            name: '管理员',
            is_active: true,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString()
          }
        }
      } else {
        // 对于其他错误，可以根据具体情况决定是否登出
        // 这里保持原有的登出逻辑，但可以考虑增加重试机制
        logout()
      }
    }
  }
  
  return {
    ...toRefs(state),
    getUserRole,
    hasPermission,
    login,
    register,
    logout,
    fetchUserInfo
  }
})